

const mqtt = require('mqtt')
const host = 'i6134ef3.cn-shenzhen.emqx.cloud'
const port = '11911'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`

// connect options
const OPTIONS = {
  clientId,
  clean: true,
  connectTimeout: 4000,
  username: 'test',
  password: 'test',
  reconnectPeriod: 1000,
}
let connectUrl = `mqtt://${host}:${port}`
const topic = 'mqtt'
const serverSocket = mqtt.connect(connectUrl, OPTIONS)
//监听服务器开启
serverSocket.on('connect', () => {
  console.log('服务器已连接')
  serverSocket.subscribe([topic + '/test_server'], () => {
    console.log(`已订阅'${topic}'`)
  })
})

serverSocket.on('error', (err) => {
  console.log('error: ', err)
})

//监听客户端发送的数据
let echoLock = false, catLock = false;
serverSocket.on('message', (topic, payload) => {
  if (!echoLock&&payload) {
    echoLock = true;
    doEcho(payload.toString()).then(() => {
      echoLock = false;
    })
  }
})

serverSocket.sendData = function (data) {
  data = data || ''
  return new Promise((resolve) => serverSocket.publish(topic + '/test_client', data, { qos: 2, retain: false }, (error) => {
    if (error) {
      console.error(error)
    }
    resolve();
  }))
}


const cp = require('child_process');

function getRealInput(data) {
  let res = data.match(/xavierStart(.*?)xavierEnd/);

  return res && res[1] ? res[1] : null;
}
function getRealOutput(data) {
  let res = 'imx6qStart' + data + 'imx6qEnd';

  return res;
}
function doCat() {
   const cat = cp.spawn('cat', ['/dev/ttySAC1']);

   cat.stdout.on('data', function (data) {
      if (!catLock && data) {
        catLock = true;
        data = data.toString();
        data = getRealInput(data);
        if (data !== null) {
          console.log("6Q recev 5G", data);
          serverSocket.sendData(data).then(() => {
            const kill = cp.spawn('kill', [cat.pid])
          })
        }
      }
   });
 
   cat.stderr.on('data', function (data) {
   });
 
   cat.on('close', function (code) {
      catLock = false;
      doCat();
   });
}

function doEcho(data) {
  data = getRealOutput(data);

  return new Promise((resolve) => cp.exec('echo ' + data + ' > /dev/ttySAC1', function (err, stdout, stderr) {
    if (err) {
      console.error(err);
    }
    console.log("6Q send data", data);
    resolve();
  }));
}
// doCat()
